﻿using Microsoft.Office.Interop.Excel;
using PdfiumViewer;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;

namespace BatchPrint.Converter;

public class ExcelToImageConverter : IImageConverter
{
    private static List<Bitmap> ConvertToImages(string excelPath)
    {
        var _excelApp = new Application { Visible = false };
        var _workbook = _excelApp.Workbooks.Open(excelPath);
        var imagePaths = new List<Bitmap>();

        try
        {
            foreach (Worksheet sheet in _workbook.Worksheets)
            {
                var imagePath = ConvertSheetToImage(sheet, 0);
                using DImage img = DImage.FromFile(imagePath);
                Bitmap bitmap = new(img);
                imagePaths.Add(bitmap);
            }

            return imagePaths;
        }
        catch (Exception ex)
        {
            throw new Exception($"转换Excel失败: {ex.Message}");
        }
        finally
        {
            if (_workbook != null)
            {
                _workbook.Close(false);
                Marshal.ReleaseComObject(_workbook);
            }

            if (_excelApp != null)
            {
                _excelApp.Quit();
                Marshal.ReleaseComObject(_excelApp);
            }
        }
    }

    private static string ConvertSheetToImage(Worksheet sheet, int pageNumber)
    {
        // 设置打印区域
        var usedRange = sheet.UsedRange;
        sheet.PageSetup.Zoom = false;
        sheet.PageSetup.FitToPagesWide = 1;

        // 导出为PDF
        var pdfPath = Path.GetTempFileName() + ".pdf";
        sheet.ExportAsFixedFormat(
            XlFixedFormatType.xlTypePDF,
            pdfPath,
            XlFixedFormatQuality.xlQualityStandard
        );

        var outputPath = Path.GetTempFileName();
        // 将PDF转换为图片
        using (var document = PdfDocument.Load(pdfPath))
        {
            var page = document.PageSizes[pageNumber];
            int width = System.Convert.ToInt32(page.Width) * 2;
            int height = System.Convert.ToInt32(page.Height) * 2;
            using var image = document.Render(pageNumber, width, height, 500, 500, PdfRenderFlags.ForPrinting);
            image.Save(outputPath, ImageFormat.Png);
        }
        File.Delete(pdfPath);
        return outputPath;
    }

    public async Task<DImage> Convert(string filePath)
    {
        await Task.Yield();
        var images = ConvertToImages(filePath);
        return images.First();
    }
}
